import plugin from '../../lib/plugins/plugin.js'
import moment from 'moment';
import { segment } from "oicq";

let dateTime = 'YYYY-MM-DD 00:00:00'; //这里定义时间刷新时间  格式是 年-月-日 时:分:秒
let daytime = 1;   //设置只获取多少天内发言的人

export class example extends plugin {
  constructor() {
    super({
      /** 功能名称 */
      name: '今日冤种',
      /** 功能描述 */
      dsc: '今日冤种',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 5000,
      rule: [
        {
          /** 命令正则匹配 */
          reg: '#?今(日|天)(的)?冤种(是谁)?$',
          /** 执行方法 */
          fnc: 'dayuanzhong'
        },
        {
          /** 命令正则匹配 */
          reg: '^#?删除今日冤种$',
          /** 执行方法 */
          fnc: 'dayuanzhong'
        },
      ]
    })
  }

  /**
   * @description: #今日冤种
   */
  async dayuanzhong(e) {
    if (e.isPrivate) {
      e.reply([`你就是我的大怨种呢~~~`, segment.face(318)])
      return false;
    }
    let key = `YZ:yuanzhong:${e.group_id}`
    //删除
    if (/#?删除今日冤种/.test(e.msg)) {
      await redis.del(key)
      e.reply("已经把这个大怨种删了哦~")
      return true;
    }

    //先看缓存中有没有数据
    let data_redis = await redis.get(key);
    let lasttime;
    let yuanzhong;
    //如果有就发缓存中的没有就随机抽取一个群友
    if (data_redis) {
      //转换缓存中的数据
      yuanzhong = JSON.parse(data_redis);
      //获取最新的最后发言时间
      lasttime = formatDate(e.group.pickMember(yuanzhong.user_id).info.last_sent_time)

    } else {
      //获取群员列表
      let mmap = await e.group.getMemberMap();
      //转换数据
      let arrMember = Array.from(mmap.values());
      // 随机数
      yuanzhong = arrMember[Math.round(Math.random() * (arrMember.length - 1))];
      //定义多少时间内发言的人
      let nowtime = new Date().getTime() / 1000 - (86400 * daytime)
      //获取发言时间
      let yztime = yuanzhong.last_sent_time
      //循环
      while (yztime <= nowtime) {
        yuanzhong = arrMember[Math.round(Math.random() * (arrMember.length - 1))];
        yztime = yuanzhong.last_sent_time
      }

      lasttime = formatDate(yuanzhong.last_sent_time)
    }

    const sex = {
      "unknown": "~",
      "female": "女",
      "male": "男"
    }

    let msg = [
      segment.image(
        `https://q1.qlogo.cn/g?b=qq&s=0&nk=${yuanzhong.user_id}`
      ),
      `【${yuanzhong.nickname}】 (${yuanzhong.user_id}) ${sex[yuanzhong.sex]} 哒哒哒~\n`, `最后发言时间：${lasttime}`
    ];

    if (data_redis) {
      msg.unshift(`今天的大冤种已经出现啦`, segment.face(46), `！！！`)
      e.reply(msg);
      return true;
    }

    msg.unshift("铛铛铛~~\n", "今天的大冤种是")

    e.reply("获取今天的大怨种ing~~")
    setTimeout(() => {
      e.reply(msg)
    }, 2500);

    var time = moment(Date.now()).add('day', 1).format(dateTime)

    var new_date = (new Date(time).getTime() - new Date().getTime()) / 1000
    //写入缓存
    redis.set(key, JSON.stringify(yuanzhong), { EX: parseInt(new_date) })

    return true;
  }
}


/**
 * @description: 时间转换
 * @return YYYY-MM-DD HH:mm:ss
 */
function formatDate(time) {
  var now = new Date(parseFloat(time) * 1000);
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (date >= 0 && date <= 9) {
    date = "0" + date;
  }
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  if (hour >= 1 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minute >= 0 && minute <= 9) {
    minute = "0" + minute;
  }
  if (second >= 0 && second <= 9) {
    second = "0" + second;
  }
  return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

